{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def subsets(index, k, N, K, ans):\n",
    "    \"枚举子集，但是不是字典序\"\n",
    "    if k == K:\n",
    "        print(ans)\n",
    "        return\n",
    "    if index == N:\n",
    "        return\n",
    "    subsets(index + 1, k, N, K, ans)\n",
    "    ans.append(index)\n",
    "    subsets(index + 1, k+1, N, K, ans)\n",
    "    ans.pop()\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[2, 3]\n",
      "[1, 3]\n",
      "[1, 2]\n",
      "[0, 3]\n",
      "[0, 2]\n",
      "[0, 1]\n"
     ]
    }
   ],
   "source": [
    "subsets(0, 0, 4, 2, [])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def subsets2(k, start, N, K, ans):\n",
    "    \"枚举子集，且字典序\"\n",
    "    if k == K:\n",
    "        print(ans)\n",
    "        return\n",
    "\n",
    "    if N - start + 1 < K - k:\n",
    "        return  # 剩余的元素不足\n",
    "\n",
    "    while start <= N:\n",
    "        ans.append(start)\n",
    "        subsets2(k + 1, start + 1, N, K, ans)\n",
    "        ans.pop()\n",
    "        start += 1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2]\n",
      "[1, 3]\n",
      "[1, 4]\n",
      "[2, 3]\n",
      "[2, 4]\n",
      "[3, 4]\n"
     ]
    }
   ],
   "source": [
    "subsets2(0, 1, 4, 2, [])"
   ]
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "2497819141e8ba68491e095adc461a03e742be7ecd39014decbc2aa0e30dc29f"
  },
  "kernelspec": {
   "display_name": "Python 3.9.12 64-bit (windows store)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
